#include "MainWindow.h"
#include <QMenuBar>
#include <QMenu>
#include <QAction>
#include <QStatusBar>
#include <QVBoxLayout>
#include <QMessageBox>
#include <QApplication>
#include <QDebug>

MainWindow::MainWindow(QWidget* parent)
    : QMainWindow(parent)
    , m_cocosWidget(nullptr)
    , m_movesLabel(nullptr)
    , m_timeLabel(nullptr)
    , m_scoreLabel(nullptr)
    , m_fpsLabel(nullptr)
    , m_moves(0)
    , m_score(0)
    , m_gameTimeSeconds(0)
    , m_gameTimer(nullptr)
    , m_gameStarted(false)
{
    setupUI();
    setupMenuBar();
    setupStatusBar();
    applyDeepinTheme();

    qDebug() << "[MainWindow] Initialized";
}

MainWindow::~MainWindow() {
    qDebug() << "[MainWindow] Destructor called";
}

void MainWindow::setupUI() {
    // 设置窗口属性
    setWindowTitle("Qt OpenGL Demo - Triangle & Hello World");
    resize(1024, 768);

    // 中央部件
    QWidget* centralWidget = new QWidget(this);
    QVBoxLayout* layout = new QVBoxLayout(centralWidget);
    layout->setContentsMargins(0, 0, 0, 0);  // 无边距，最大化渲染区域

    // OpenGL渲染窗口
    m_cocosWidget = new CocosWidget(this);
    m_cocosWidget->setMinimumSize(800, 600);
    layout->addWidget(m_cocosWidget);

    setCentralWidget(centralWidget);

    // 连接信号
    connect(m_cocosWidget, &CocosWidget::fpsChanged,
            this, &MainWindow::onFpsChanged);
    connect(m_cocosWidget, &CocosWidget::cardClicked,
            this, &MainWindow::onCardClicked);
}

void MainWindow::setupMenuBar() {
    // 游戏菜单
    QMenu* gameMenu = menuBar()->addMenu(tr("游戏(&G)"));

    QAction* actNewGame = new QAction(tr("新游戏(&N)"), this);
    actNewGame->setShortcut(QKeySequence::New);  // Ctrl+N
    connect(actNewGame, &QAction::triggered, this, &MainWindow::onNewGame);
    gameMenu->addAction(actNewGame);

    QAction* actRestart = new QAction(tr("重新开始(&R)"), this);
    actRestart->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_R));
    connect(actRestart, &QAction::triggered, this, &MainWindow::onRestartGame);
    gameMenu->addAction(actRestart);

    gameMenu->addSeparator();

    QAction* actUndo = new QAction(tr("撤销(&U)"), this);
    actUndo->setShortcut(QKeySequence::Undo);  // Ctrl+Z
    connect(actUndo, &QAction::triggered, this, &MainWindow::onUndo);
    gameMenu->addAction(actUndo);

    gameMenu->addSeparator();

    QAction* actExit = new QAction(tr("退出(&X)"), this);
    actExit->setShortcut(QKeySequence::Quit);  // Ctrl+Q
    connect(actExit, &QAction::triggered, this, &MainWindow::onExit);
    gameMenu->addAction(actExit);

    // 帮助菜单
    QMenu* helpMenu = menuBar()->addMenu(tr("帮助(&H)"));

    QAction* actAbout = new QAction(tr("关于(&A)"), this);
    connect(actAbout, &QAction::triggered, this, &MainWindow::onAbout);
    helpMenu->addAction(actAbout);
}

void MainWindow::setupStatusBar() {
    // 创建状态栏标签
    m_movesLabel = new QLabel(tr("移动: 0"), this);
    m_timeLabel = new QLabel(tr("时间: 00:00"), this);
    m_scoreLabel = new QLabel(tr("分数: 0"), this);
    m_fpsLabel = new QLabel(tr("FPS: 0"), this);

    // 添加到状态栏
    statusBar()->addWidget(m_movesLabel);
    statusBar()->addWidget(m_timeLabel);
    statusBar()->addWidget(m_scoreLabel);
    statusBar()->addPermanentWidget(m_fpsLabel);  // 右侧显示

    // 创建游戏计时器
    m_gameTimer = new QTimer(this);
    connect(m_gameTimer, &QTimer::timeout, this, &MainWindow::updateGameTime);
}

void MainWindow::applyDeepinTheme() {
    // 简单的Deepin风格样式
    // 实际使用时，Deepin的Qt主题插件会自动处理
    // 这里提供一个基础的深色主题样式作为示例

#ifdef __linux__
    // 检测是否为深色模式（简化版）
    QPalette palette = QApplication::palette();
    bool isDarkMode = palette.color(QPalette::Window).lightness() < 128;

    if (isDarkMode) {
        setStyleSheet(R"(
            QMenuBar {
                background-color: #2d2d2d;
                color: #ffffff;
            }
            QMenuBar::item:selected {
                background-color: #3d8ac7;
            }
            QMenu {
                background-color: #2d2d2d;
                color: #ffffff;
                border: 1px solid #555555;
            }
            QMenu::item:selected {
                background-color: #3d8ac7;
            }
            QStatusBar {
                background-color: #252525;
                color: #b0b0b0;
            }
            QLabel {
                color: #b0b0b0;
            }
        )");
    }
#endif

    qDebug() << "[MainWindow] Deepin theme applied";
}

// =============================================================================
// 槽函数实现
// =============================================================================

void MainWindow::onNewGame() {
    qDebug() << "[MainWindow] New game";

    // 重置游戏状态
    m_moves = 0;
    m_score = 0;
    m_gameTimeSeconds = 0;
    m_gameStarted = true;

    updateStatusBar();

    // 启动计时器
    m_gameTimer->start(1000);  // 每秒更新
}

void MainWindow::onRestartGame() {
    qDebug() << "[MainWindow] Restart game";
    onNewGame();
}

void MainWindow::onUndo() {
    qDebug() << "[MainWindow] Undo";
    // TODO: 实现撤销逻辑
    QMessageBox::information(this, tr("撤销"),
                           tr("撤销功能待实现\n这是一个演示项目"));
}

void MainWindow::onExit() {
    qDebug() << "[MainWindow] Exit";
    close();
}

void MainWindow::onAbout() {
    QString aboutText = tr(
        "<h3>Qt OpenGL Demo</h3>"
        "<p>Qt 原生 OpenGL 渲染演示项目</p>"
        "<p>版本: 1.0.0</p>"
        "<hr>"
        "<p><b>技术栈:</b></p>"
        "<ul>"
        "<li>Qt %1 (UI框架)</li>"
        "<li>QOpenGLWidget (OpenGL集成)</li>"
        "<li>OpenGL 3.3 Core (渲染)</li>"
        "<li>GLSL Shaders (着色器)</li>"
        "<li>QPainter (文字渲染)</li>"
        "</ul>"
        "<p><b>功能:</b></p>"
        "<ul>"
        "<li>使用Shader渲染旋转的彩色三角形</li>"
        "<li>使用QPainter绘制Hello World文字</li>"
        "<li>实时FPS显示</li>"
        "</ul>"
        "<p><b>支持平台:</b> Deepin Linux, macOS, Windows</p>"
        "<hr>"
        "<p>© 2024 Qt OpenGL示例</p>"
    ).arg(QT_VERSION_STR);

    QMessageBox::about(this, tr("关于"), aboutText);
}

void MainWindow::onFpsChanged(float fps) {
    m_fpsLabel->setText(tr("FPS: %1").arg(static_cast<int>(fps)));
}

void MainWindow::onCardClicked(float x, float y) {
    qDebug() << "[MainWindow] Card clicked at:" << x << "," << y;

    // 演示：每次点击增加移动次数和分数
    if (m_gameStarted) {
        m_moves++;
        m_score += 10;
        updateStatusBar();
    }
}

void MainWindow::updateGameTime() {
    if (!m_gameStarted) return;

    m_gameTimeSeconds++;
    int minutes = m_gameTimeSeconds / 60;
    int seconds = m_gameTimeSeconds % 60;

    m_timeLabel->setText(tr("时间: %1:%2")
                        .arg(minutes, 2, 10, QChar('0'))
                        .arg(seconds, 2, 10, QChar('0')));
}

void MainWindow::updateStatusBar() {
    m_movesLabel->setText(tr("移动: %1").arg(m_moves));
    m_scoreLabel->setText(tr("分数: %1").arg(m_score));
}
